var gpsStarted = false;
var wait = 10;
var host = "ws://localhost:9000/";

socket = new WebSocket(host);
function connectGPSD() {		
	if (socket.readyState !== 1 && this.wait == 0) {
//		if (typeof socket === "undefined") {
			socket = new WebSocket(host);
//		}
		this.wait = 10;
	} else if (socket.readyState == 1) {
		socket.send("PING");
	} else {
		postMessage("nofix");
	}
	
	socket.onopen = function(msg) { 
		if (socket.readyState == 1) {
			this.gpsStarted = true;
			// this is the initial ping
			setTimeout(socket.send("PING"), 200);
		}
	};

	socket.onclose = function(msg) {
		this.gpsStarted = false; 
		this.wait = 0;
	};
	 
	socket.onerror = function(msg) {
		this.gpsStarted = false;
	}

	socket.onmessage = function(msg) { 
		postMessage(msg.data);
	};

	this.wait = parseInt(this.wait) - 1;
	setTimeout(connectGPSD, 950);		
}

connectGPSD();
	
